package org.basis.netty.chat.rpc.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.basis.netty.chat.protocol.MessageCodecSharable;
import org.basis.netty.chat.protocol.ProcotolFrameDecoder;
import org.basis.netty.chat.protocol.RpcResponseMessageHandler;

import java.net.InetSocketAddress;

/**
 * RPC客户端
 *
 * @author Mr_wenpan@163.com 2021/09/28 16:06
 */
@Slf4j
public class RpcClient {

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup group = new NioEventLoopGroup();

        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);
        MessageCodecSharable messageCodecSharable = new MessageCodecSharable();
        // rpc响应消息处理器handler
        RpcResponseMessageHandler rpcResponseMessageHandler = new RpcResponseMessageHandler();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);

            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                // 建立连接后为该client channel添加handler
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 添加帧解码器，防止消息黏包半包
                    pipeline.addLast(new ProcotolFrameDecoder());
                    pipeline.addLast(loggingHandler);
                    // 按照自定义协议对消息进行编解码
                    pipeline.addLast(messageCodecSharable);
                    // 添加rpc响应消息handler
                    pipeline.addLast(rpcResponseMessageHandler);
                }
            });

            Channel channel = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync().channel();
            // 同步等待channel关闭
            channel.closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }

}
